package com.leetcode.problems039;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/combination-sum/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    List<List<Integer>> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        combinationSum1(candidates,target,new ArrayList<>(),0);
        return list;
    }


    public void combinationSum(int[] candidates, int target,List<Integer> res,int i) {
        if(target == 0) {
            list.add(new ArrayList<>(res));
            return;
        }
        if(i == candidates.length){
            return;
        }
        //不选择当前的数字
        combinationSum(candidates,target,res,i + 1);
        //可以选择当前的数字
        if(candidates[i] <= target) {
            int cur = candidates[i];
            res.add(cur);
            combinationSum(candidates,target - cur,res,i);
            res.remove(res.size() - 1);
        }
    }


    public void combinationSum1(int[] candidates, int target,List<Integer> res,int index) {
        if(target == 0) {
            list.add(new ArrayList<>(res));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            //可以选择当前的数字
            if(candidates[i] <= target) {
                int cur = candidates[i];
                res.add(cur);
                combinationSum1(candidates,target - cur,res,i);
                res.remove(res.size() - 1);
            }
        }

    }


    public static void main(String[] args) {
        int[] candidates = {2 , 3, 6, 7};
        int target = 7;
        System.out.println(new Solution().combinationSum(candidates,target));;
    }
}
